package com.sf.fy.uav.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.fy.uav.common.awt.JwtUtil;
import com.sf.fy.uav.common.enums.ServicePrefixEnum;
import com.sf.fy.uav.common.enums.TaskStatusNum;
import com.sf.fy.uav.common.request.order.task.TaskRequest;
import com.sf.fy.uav.common.response.user.TaskResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.PhoneDesensitizationUtil;
import com.sf.fy.uav.common.utils.RedisPrefixKey;
import com.sf.fy.uav.good.entity.GoodsType;
import com.sf.fy.uav.good.entity.TaskGoods;
import com.sf.fy.uav.good.mapper.GoodsTypeMapper;
import com.sf.fy.uav.good.mapper.TaskGoodsMapper;
import com.sf.fy.uav.sms.rest.WxAppletRest;
import com.sf.fy.uav.task.controller.TaskStatusLogRest;
import com.sf.fy.uav.task.entity.Airport;
import com.sf.fy.uav.task.entity.Task;
import com.sf.fy.uav.task.entity.TaskStatusLog;
import com.sf.fy.uav.task.mapper.AirportMapper;
import com.sf.fy.uav.task.mapper.TaskMapper;
import com.sf.fy.uav.task.mapper.TaskStatusLogMapper;
import com.sf.fy.uav.task.service.ITaskService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-04-04
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {
    private static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskGoodsMapper taskGoodsMapper;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private TaskStatusLogMapper taskStatusLogMapper;


    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    @Autowired
    private TaskStatusLogRest taskStatusLogRest;

    @Autowired
    private WxAppletRest wxAppletRest;



    @Value("${wx.update-status-template-id:DyZzQXtOw2iXdd63ZETf-40AVO_q8Ip305yplDfs2qc}")
    private String updateStatusTemplateId;

    private final static String PHONE_VERIFY = "^1[0-9]{10}$";


    @Override
    public List<TaskResponse> getIngTasks(String statuses) {
        String userId = JwtUtil.getUserId();
        List<Task> tasks = taskMapper.selectList(new QueryWrapper<Task>().eq("user_id", userId).in("status", Arrays.asList(StringUtils.deleteWhitespace(statuses).split(","))).orderByDesc("create_time"));
        List<TaskResponse> taskResponses = this.dto(tasks);
        return taskResponses;
    }

    @Override
    public List<TaskResponse> getAllTasks() {
        String userId = JwtUtil.getUserId();
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("user_id", userId);
        taskQueryWrapper.orderByDesc("create_time");
        List<Task> tasks = taskMapper.selectList(taskQueryWrapper);
        List<TaskResponse> taskResponses = this.dto(tasks);
        return taskResponses;
    }


    private List<TaskResponse> dto(List<Task> tasks) {
        List<TaskResponse> taskResponses = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tasks)) {
            List<String> taskIds = tasks.stream().map(task -> task.getId()).collect(Collectors.toList());
            List<String> airportIds = tasks.stream().map(task -> task.getAirportId()).collect(Collectors.toList());
            QueryWrapper<TaskGoods> taskGoodsQueryWrapper = new QueryWrapper<>();
            taskGoodsQueryWrapper.in("task_id", taskIds);
            List<TaskGoods> taskGoods = taskGoodsMapper.selectList(taskGoodsQueryWrapper);

            QueryWrapper<Airport> airportQueryWrapper = new QueryWrapper<>();
            airportQueryWrapper.in("id", airportIds);
            List<Airport> airports = airportMapper.selectList(airportQueryWrapper);

            QueryWrapper<GoodsType> goodsTypeQueryWrapper = new QueryWrapper<>();
            List<GoodsType> goodsTypes = goodsTypeMapper.selectList(goodsTypeQueryWrapper);

            tasks.forEach(task -> {
                TaskResponse taskResponse = BeanUtil.copyProperties(task, TaskResponse.class);
                List<TaskGoods> taskResponses1 = taskGoods.stream().filter(taskGoods1 -> taskGoods1.getTaskId().equals(task.getId())).collect(Collectors.toList());
                List<Airport> airports1 = airports.stream().filter(airport -> airport.getId().equals(task.getAirportId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(taskResponses1)) {
                    List<GoodsType> goodsTypes1 = goodsTypes.stream().filter(goodsType -> goodsType.getId().equals(taskResponses1.get(0).getGoodsTypeId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(goodsTypes1)) {
                        taskResponse.setGoodsTypeName(goodsTypes1.get(0).getName());
                    }
                }
                if (!CollectionUtils.isEmpty(airports1)) {
                    Airport airport = airports1.get(0);
                    String locationName = airport.getName();
                    taskResponse.setLocationName(locationName);
                }
                if (!ObjectUtils.isEmpty(task.getPhoneCode()) && !ObjectUtils.isEmpty(task.getPhoneNum()) && !task.getPhoneNum().matches(PHONE_VERIFY)) {
                    taskResponse.setPhoneNum(ObjectUtils.isEmpty(task.getPhoneCode()) ? task.getPhoneNum() : task.getPhoneCode() + "-" + task.getPhoneNum());
                }
                if (ObjectUtils.isEmpty(task.getPhoneCode()) && !ObjectUtils.isEmpty(task.getPhoneNum()) && task.getPhoneNum().matches(PHONE_VERIFY)) {
                    taskResponse.setPhoneNum(PhoneDesensitizationUtil.phoneDesensitization(task.getPhoneNum()));
                }
                taskResponses.add(taskResponse);
            });
        }
        return taskResponses;
    }

    @Override
    public void addTask(TaskRequest taskRequest) {
        Task task = BeanUtil.copyProperties(taskRequest, Task.class);
        taskMapper.insert(task);
    }
}
